<?php

namespace Theatre\Client;

class Booking extends \Theatre\Controller {
	protected function beforeFilter() {
		if (!$this->userExists()) {
			$this->redirect('/user/login');
		}
	}


	/**
	 * Default method, list theatre halls and shows
	 */
	function index() {
		$data = $this->model('TicketAPI')->getShowSchedule();

		$this->set(array(
			'halls' => !empty($data['status']) && $data['status'] == 'success' ? $data['schedule'] : array()
		));
	}


	/**
	 * Get the seats for the specified show and hall
	 */
	public function get() {
		$this->view('JSON');

		if (empty($this->params['hallId']) || !is_numeric($this->params['hallId'])) {
			$this->set(array(
				'status'  => 'error',
				'message' => 'No Hall Id given'
			));
		}

		if (empty($this->params['showId']) || !is_numeric($this->params['showId'])) {
			$this->set(array(
				'status'  => 'error',
				'message' => 'No Show Id given'
			));
		}

		if (empty($this->params['representationId']) || !is_numeric($this->params['representationId'])) {
			$this->set(array(
				'status'  => 'error',
				'message' => 'No Representation Id given'
			));
		}

		$data = $this->model('TicketAPI')->getAllSeats(
			$this->params['hallId'],
			$this->params['showId'],
			$this->params['representationId'],
			date('Y-m-d')
		);

		if (empty($data) || empty($data['status']) || $data['status'] != 'success') {
			$this->set(array(
				'status'                   => 'error',
				'available_seats'          => 0,
				'booked_seats'             => array(),
				'unconfirmed_booked_seats' => array()
			));

			return;
		}

		$this->set(array(
			'status'                   => 'success',
			'available_seats'          => $data['seats']['available_seats'],
			'booked_seats'             => $data['seats']['booked_seats'],
			'unconfirmed_booked_seats' => $data['seats']['unconfirmed_booked_seats']
		));
	}


	/**
	 * Before render callback
	 */
	protected function beforeRender() {
		parent::beforeRender();

		if (!$this->asyncRequest()) {
			$this->set(array('loggedInUser' => $this->getLoggedInUser()));
		}
	}
}
